import moment from 'moment'

/*
 *   des:        格式化时间
 *   @return:    {yyyy-MM-dd HH:mm:ss}
 *   ex:         2018-01-01 08:00:00
 */
Date.prototype.formatDate = function (formatStr) {
  if (!formatStr || typeof formatStr !== 'string') formatStr = 'yyyy-MM-dd HH:mm'
  const dict = {
    'yyyy': this.getFullYear(),
    'M': this.getMonth() + 1,
    'd': this.getDate(),
    'H': this.getHours(),
    'm': this.getMinutes(),
    's': this.getSeconds(),
    'f': this.getMilliseconds(),
    'MM': ('' + (this.getMonth() + 101)).substr(1),
    'dd': ('' + (this.getDate() + 100)).substr(1),
    'HH': ('' + (this.getHours() + 100)).substr(1),
    'mm': ('' + (this.getMinutes() + 100)).substr(1),
    'ss': ('' + (this.getSeconds() + 100)).substr(1),
    'fff': ('' + (this.getMilliseconds() + 1000)).substr(1)
  }
  return formatStr.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?|fff?)/g, function () {
    return dict[arguments[0]]
  })
}

export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function downloadFile (obj, name, suffix) {
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const tm = moment().format('YYYY-MM-DD')
  // parseTime(new Date()) + '-' +
  const fileName = tm + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  // return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false    //判断权限
  return true
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

export function notNull (st) {
  return ![undefined, null, '', false, NaN].includes(st)
}

export function getDateTimeData () {
  const now = new Date()
  const year = now.getFullYear()
  let month = now.getMonth() + 1
  let date = now.getDate()

  if (month < 10) month = '0' + month
  if (date < 10) date = '0' + date

  const today = `${year}-${month}-${date}`
  const arr = []
  for (let i = 0; i < 24; i += 1) {
    const hm = i < 10 ? `0${i}:00` : `${i}:00`
    arr.push(`${today}\n${hm}`)
  }

  return arr
}

export function formatDate (value) {
  const date = new Date(value)
  const y = date.getFullYear()
  let MM = date.getMonth() + 1
  MM = MM < 10 ? ('0' + MM) : MM
  let d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  let h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  let m = date.getMinutes()
  m = m < 10 ? ('0' + m) : m
  let s = date.getSeconds()
  s = s < 10 ? ('0' + s) : s
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
}

function columnsForEach (columns, field, renderContent) {
  try {
    columns.forEach((item) => {
      if (item.dataIndex === field) {
        item.customRender = renderContent

        // console.log(item)
        throw '结束循环'// 在这里抛出异常
      }
      if (item.children) {
        columnsForEach(item.children, field, renderContent)
      }
    })
  } catch (e) {
    // console.log(e)
  }
}

/**
 *处理表格行合并
 * 参数：data表格数据
 * 参数：field 合并的字段
 * 参数：columns 表格原来的列
 * newColumns 引入 this.columns
 * 返回 data表格数据 columns 表格列
 *
 */
export function dealTable (data, field, columns) {
  const rowSpanArr = []
  let index1 = 0
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      rowSpanArr.push(1)
      index1 = i
    } else {
      if (data[i][field] === data[i - 1][field]) {
        rowSpanArr[index1] += 1
        rowSpanArr.push(0)
      } else {
        rowSpanArr.push(1)
        index1 = i
      }
    }
  }
  // console.log(rowSpanArr)

  const renderContent = (value, row, index) => {
    const obj = {
      children: value,
      attrs: {}
    }
    obj.attrs.rowSpan = rowSpanArr[index]
    return obj
  }

  columnsForEach(columns, field, renderContent)

  // try{
  //   columns.forEach((item)=>{
  //     if(item.dataIndex === field){
  //       item.customRender = renderContent
  //
  //       console.log(item)
  //       throw '结束循环'//在这里抛出异常
  //     }
  //   })
  // } catch (e) {
  //   console.log(e)
  // }

  // console.log(columns)
  return {
    columns,
    data
  }
}

/**
 *判断是否是一个数字
 *
 */
export function isNotANumber (inputData) {
  // isNaN(inputData)不能判断空串或一个空格
  // 如果是一个空串或是一个空格，而isNaN是做为数字0进行处理的，而parseInt与parseFloat是返回一个错误消息，这个isNaN检查不严密而导致的。
  if (parseFloat(inputData).toString() == 'NaN') {
    // alert(“请输入数字……”);
    return false
  } else {
    return true
  }
}

/**
 *判断是否是有意义
 *
 */
export function isEffectiveValue (inputData) {
  // isNaN(inputData)不能判断空串或一个空格
  // 如果是一个空串或是一个空格，而isNaN是做为数字0进行处理的，而parseInt与parseFloat是返回一个错误消息，这个isNaN检查不严密而导致的。
  if (inputData === null || inputData === undefined || inputData !== inputData) {
    return false
  } else {
    return true
  }
}
// 去掉数组内重复的对象
export function deteleObject (obj) {
  var uniques = []
  var stringify = {}
  for (var i = 0; i < obj.length; i++) {
    var keys = Object.keys(obj[i])
    keys.sort(function (a, b) {
      return (Number(a) - Number(b))
    })
    var str = ''
    for (var j = 0; j < keys.length; j++) {
      str += JSON.stringify(keys[j])
      str += JSON.stringify(obj[i][keys[j]])
    }
    if (!stringify.hasOwnProperty(str)) {
      uniques.push(obj[i])
      stringify[str] = true
    }
  }
  uniques = uniques
  return uniques
}
/**
 *判断是否有长度不为零的children,
 * 如果children长度为0，则去掉children属性
 *
 */
function filterRowChildren (tableData, field) {
  if (!field) {
    field = 'children'
  }
  return tableData.map(
    function (item) {
      let newItem = {}
      if (item[field]) {
        if (item[field].length > 0) {
          newItem = Object.assign({}, item)
          newItem[[field]] = filterRowChildren(item[[field]])
        } else {
          newItem = Object.assign({}, item)
          delete newItem[[field]]
        }
      } else {
        newItem = Object.assign({}, item)
      }
      return newItem
    }
  )
}
export function convertCurrency (money) {
  // 汉字的数字
  var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖')
  // 基本单位
  var cnIntRadice = new Array('', '拾', '佰', '仟')
  // 对应整数部分扩展单位
  var cnIntUnits = new Array('', '万', '亿', '兆')
  // 对应小数部分单位
  var cnDecUnits = new Array('角', '分', '毫', '厘')
  // 整数金额时后面跟的字符
  var cnInteger = '整'
  // 整型完以后的单位
  var cnIntLast = '元'
  // 最大处理的数字
  var maxNum = 999999999999999.9999
  // 金额整数部分
  var integerNum
  // 金额小数部分
  var decimalNum
  // 输出的中文金额字符串
  var chineseStr = ''
  // 分离金额后用的数组，预定义
  var parts
  if (money == '') { return '' }
  money = parseFloat(money)
  if (money >= maxNum) {
    // 超出最大处理数字
    return ''
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转换为字符串
  money = money.toString()
  if (money.indexOf('.') == -1) {
    integerNum = money
    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0
    var IntLen = integerNum.length
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1)
      var p = IntLen - i - 1
      var q = p / 4
      var m = p % 4
      if (n == '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1)
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum == '') {
    chineseStr += cnInteger
  }
  return chineseStr
}

// 数字转换大写
export function turnUpcase (n) {
  var fraction = ['角', '分']
  var digit = [
    '零', '壹', '贰', '叁', '肆',
    '伍', '陆', '柒', '捌', '玖'
  ]
  var unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  var head = n < 0 ? '欠' : ''
  n = Math.abs(n)
  var s = ''
  for (var i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  s = s || '整'
  n = Math.floor(n)
  for (var i = 0; i < unit[0].length && n > 0; i++) {
    var p = ''
    for (var j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p
      n = Math.floor(n / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  return head + s.replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '')
}

/**
 *字段 复制/替换 'copy' ,'clip'
 *
 *
 */
function treeTransition (arrData, fieldMap, dealType) {
  return arrData.map(
    function (item) {
      let newItem = {}
      for (const key in fieldMap) {
        item[key] = item[fieldMap[key]]
      }
      newItem = Object.assign({}, item)
      newItem.children = treeTransition(item.children, fieldMap)
      return newItem
    }
  )
}

/*
* @param {*} value 数值
* @param {*} digits 保留小数位数
* @param {*} returnStr 是否保留字符串
*/
export function formatValue (value, digits, returnStr = false) {
  if (returnStr) {
    return parseFloat(value).toFixed(digits)
  }
  return parseFloat(parseFloat(value).toFixed(digits))
}
/**
 * 函数表示将传入数值表现为一个合理数值展示，是将钱数转换成万元显示，保留0位小数，亿以上2位小数
 * @param {*} value 数值
 * @param {*} isWanyuan 数值是否已经转换为万
 * @param {*} defaultUnit 单位
 */
export function getDigitsValueObject (value, isWanyuan = false, defaultUnit) {
  let number
  if (isWanyuan) {
    number = parseFloat(value * 10000)
  }
  number = parseFloat(value)
  let unit
  if (number >= 100000000 || number <= -100000000) {
    number = (Math.round(number / 1000000) / 100).toFixed(2)
    unit = `亿${defaultUnit}`
  } else if ((number >= 10000 && number < 100000000) || (number > -100000000 && number <= -10000)) {
    number = (Math.round(number / 100) / 100).toFixed(0)
    unit = `万${defaultUnit}`
  } else {
    number = (Math.round(number * 100) / 100).toFixed(0)
    unit = defaultUnit
  }
  return { value: number, unit: unit }
}

/**
 * 十六进制颜色转换为带透明度的颜色
 * @param _color 十六进制颜色
 * @param _opactity 透明度
 * @returns {string} rgba
 */
export function hexToRGBA (_color, _opacity) {
  let sColor = _color.toLowerCase()
  // 十六进制颜色值的正则表达式
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      let sColorNew = '#'
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    // 处理六位的颜色值
    const sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    return 'rgba(' + sColorChange.join(',') + ',' + _opacity + ')'
  }
  return sColor
}

function RandomNumBoth (Min, Max) {
  var Range = Max - Min
  var Rand = Math.random()
  var num = Min + Math.round(Rand * Range) // 四舍五入
  return num
}

export function getRandomDateBetween (Str) { // 生成当前时bai间一个月内的随机时间。
  var date = new Date()
  var e = date.getTime()// 当前时间的秒数
  var f = date.getTime() - (30 * 24 * 60 * 60 * 1000) // 30天之前du的秒数，
  // 这里zhi是注释打印不用看 console.log(a.Format('yyyy-MM-dd hh:mm:ss'),b.Format('yyyy-MM-dd hh:mm:ss'))
  // 这里是注释打印不用看console.log(new Date(this.RandomNumBoth(f,e)).Format('yyyy-MM-dd hh:mm:ss'))
  return new Date(RandomNumBoth(f, e)).formatDate(Str)
// Store.RandomNumBoth(当前时间秒数，30天之前的时间秒数),我这是react语法在这调用加类名(Store)，你们是别的就直接 this,RandomNumBoth
}

/**
 * 将简单结构数据转换成树状结构
 * @param {object} setting 设置节点的 idKey\pIdKey\children
 * @param {array} sNodes 数据数组
 * @return {array} 树状解构数据
 */
export function transformToTreeFormat (setting, sNodes) {
  setting = setting || {}
  let i
  let l
  const key = setting.idKey || 'id' // 当前节点的唯一key名
  const parentKey = setting.pIdKey || 'pid' // 指向的父节点唯一key名
  const childKey = setting.children || 'children' // 子元素的key名

  if (!key || key === '' || !sNodes) return []

  if (Array.isArray(sNodes)) {
    const r = []
    const tmpMap = []
    for (i = 0, l = sNodes.length; i < l; i += 1) {
      tmpMap[sNodes[i][key]] = sNodes[i]
    }
    for (i = 0, l = sNodes.length; i < l; i += 1) {
      if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] !== sNodes[i][parentKey]) {
        if (!tmpMap[sNodes[i][parentKey]][childKey]) {
          tmpMap[sNodes[i][parentKey]][childKey] = []
        }
        tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i])
      } else {
        r.push(sNodes[i])
      }
    }
    return r
  }

  return [sNodes]
}

export function filterCoordinate (data) {
  if (!Array.isArray(data) || data.length === 0) return []
  return data.filter(({ lat, lgt }) => notNull(lat) && notNull(lgt)).map(({ lat, lgt, ...props }) => ({ lgtd: lat, lttd: lgt, ...props }))
}

export function obj2Kv (obj) {
  if (Object.entries(obj).length > 0) {
    return Object.entries(obj).reduce((arr, [k, v]) => arr.concat(encodeURIComponent(k) + '=' + encodeURIComponent(v)), []).join('&')
  }
  return ''
}

export default {
  transformToTreeFormat,
  filterCoordinate,
  moment,
  timeFix,
  welcome,
  triggerWindowResizeEvent,
  handleScrollHeader,
  removeLoadingAnimate,
  downloadFile,
  isAuth,
  treeDataTranslate,
  notNull,
  getDateTimeData,
  dealTable,
  isNotANumber,
  filterRowChildren,
  isEffectiveValue,
  convertCurrency,
  formatDate,
  treeTransition,
  formatValue,
  getDigitsValueObject,
  turnUpcase,
  hexToRGBA,
  getRandomDateBetween,
  deteleObject,
  obj2Kv
}
